package com.shd.day02;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.BiConsumer;
import java.util.function.BiPredicate;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.IntFunction;
import java.util.function.LongPredicate;
import java.util.function.Predicate;
import java.util.function.Supplier;

import com.shd.day01.Apple;

/**
 * @author S5343
 * @date 2018年7月20日下午11:28:20
 */
public class Usage {

	// Predicate函数使用

	private static List<Apple> filter(List<Apple> source, Predicate<Apple> predicate) {
		List<Apple> result = new ArrayList<>();
		for (Apple apple : source) {
			if (predicate.test(apple)) {
				result.add(apple);
			}
		}
		return result;
	}

	private static List<Apple> filterByWeight(List<Apple> source, LongPredicate predicate) {
		List<Apple> result = new ArrayList<>();
		for (Apple apple : source) {
			if (predicate.test(apple.getWeight())) {
				result.add(apple);
			}
		}
		return result;
	}

	private static List<Apple> filterByPredicate(List<Apple> source, BiPredicate<String, Long> predicate) {
		List<Apple> result = new ArrayList<>();
		for (Apple apple : source) {
			if (predicate.test(apple.getColor(), apple.getWeight())) {
				result.add(apple);
			}
		}
		return result;
	}

	// Consume函数
	public static void simpleTestConsumer(List<Apple> source, Consumer<Apple> consumer) {
		for (Apple apple : source) {
			consumer.accept(apple);
		}
	}

	public static void simpleBiConsumer(List<Apple> source, String c, BiConsumer<Apple, String> consumer) {
		for (Apple apple : source) {
			consumer.accept(apple, c);
		}
	}

	// Function
	private static String testFunction(Apple apple, Function<Apple, String> function) {
		return function.apply(apple);
	}

	private static Apple createApple(Supplier<Apple> supplier) {
		return supplier.get();
	}

	public static void main(String[] args) {
		List<Apple> list = Arrays.asList(new Apple("green", 150), new Apple("red", 200), new Apple("green", 200));
		List<Apple> result = filterByWeight(list, w -> w > 100);
		List<Apple> result1 = filterByPredicate(list, (s, w) -> s.equals("green") && w > 100);
		simpleTestConsumer(list, a -> System.out.println(a));

		simpleBiConsumer(list, "XXX", (a, s) -> System.out.println(s + a.getColor() + ":Weight=>" + a.getWeight()));
		testFunction(new Apple("red", 100), (a) -> a.toString());

		IntFunction<Double> f = i -> i * 100.0D;
		f.apply(10);

		// Suppiler
		Supplier<String> supplier = String::new;
		System.out.println(supplier.get().getClass());

		Apple apple = createApple(() -> new Apple("Red", 199));
	}
}
